<template>
  <view class="page">
    <view v-if="$data.info">
      <view class="top">
        <view class="basic">
          <view class="basic_img">
            <image :src="$data.info._picurl" />
          </view>
          <view class="basic_content">
            <view class="basic_content--title">
              {{ $data.info.serviceTitle }}
            </view>
            <view class="basic_content--price text-price">
              {{ $data.info.firstTotalPrice }}
            </view>
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 保障 </view>
          <view class="row_right">
            <view class="flex align-center flex-warp">
              <view
                class="margin-right"
                v-for="(item, index) of $data.info.serviceSnapshot
                  .serviceTagNameArr"
                :key="index"
              >
                <up-icon
                  name="checkmark-circle"
                  color="#111111"
                  labelColor="#111111"
                  :label="item"
                  :size="18"
                  :labelSize="16"
                ></up-icon>
              </view>
            </view>
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 温馨提示 </view>
          <view class="row_right">
            {{ removeHtmlTags($data.info.serviceSnapshot.tips) }}
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 订单总价 </view>
          <view class="row_right text-price">{{ $data.info.totalPrice }}</view>
        </view>
        <view class="row">
          <view class="row_left"> 优惠 </view>
          <view class="row_right text-price">
            -{{ $data.info.couponPrice }}
          </view>
        </view>
        <!-- <view class="row" v-if="$data.info.fast">
            <view class="row_left"> 加急 </view>
            <view class="row_right text-price">
              {{ $data.info.fast }}
            </view>
          </view> -->
        <view class="row">
          <view class="row_left"> 实付金额 </view>
          <view class="row_right">
            <text class="text-price row_right--price">
              {{ $data.info.firstTotalPrice }}
            </text>
          </view>
        </view>
      </view>
      <view class="margin-top padding-lr bg-white">
        <view v-if="false" class="row">
          <view class="row_left"> 服务时间 </view>
          <view class="row_right">
            {{ $data.info._firstStartServicedAt }}
          </view>
        </view>
        <view v-if="false" class="row">
          <view class="row_left"> 服务地址 </view>
          <view class="row_right">
            {{ $data.info.addressSnapshot.locationAddress }}
          </view>
        </view>
        <view v-if="false" class="row">
          <view class="row_left"> 联系人 </view>
          <view class="row_right">
            <text> {{ $data.info.addressSnapshot.name }}</text>
            <text v-if="$data.info.addressSnapshot">
              ({{ $data.info.addressSnapshot.sex == 1 ? "先生" : "女士" }})
            </text>
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 订单编号 </view>
          <view class="row_right">
            <view class="flex justify-between align-center">
              <view>
                {{ $data.info.localNo }}
              </view>
              <view class="copy" @tap="onCopy($data.info.localNo)">复制</view>
            </view>
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 下单时间 </view>
          <view class="row_right">
            {{ $data.info._createdAt }}
          </view>
        </view>
      </view>
      <!-- 底部按钮 -->
      <view class="foot foot_box">
        <block v-if="isDown">
          <view class="btn btn_down">服务已下架</view>
        </block>
        <block v-else>
          <block v-if="$data.info.firstStatus == orderStatus.cancel">
            <view class="btn btn_save btn_pay" @tap="onReset">重新下单</view>
          </block>
          <block v-else>
            <!-- <view class="btn btn_cancel" @tap="onJump(orderActionEnum.refund)">
              申请退款
            </view> -->
            <mg-pay-button
              :mode="sdkData.mode"
              :orderId="sdkData.orderId"
              :orderStatus="sdkData.orderStatus"
              :refundId="sdkData.refundId"
              :refundTotalAmount="sdkData.refundTotalAmount"
              :applyRefundParams="sdkData.applyRefundParams"
              :localNo="$data.localNo"
              :douYinPayJson="$data.douYinPayJson"
              :workSecondPrice="$data.workSecondPrice"
              :goodsType="$data.goodsType"
            ></mg-pay-button>
            <view
              class="btn btn_save"
              @tap="onJump(orderActionEnum.reservation)"
            >
              预约
            </view>
          </block>
        </block>
      </view>
    </view>
    <PopupLogin />
  </view>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, nextTick, computed } from "vue";
import { onLoad, onShow, onHide, onReady, onUnload } from "@dcloudio/uni-app";
import { cancelOrder, getOrderDetail } from "../../../../api/Interface/order";
import errorCode from "../../../../utils/http/errorCode";
import dayjs from "dayjs";
import "dayjs/locale/zh-cn";
import duration from "dayjs/plugin/duration";
import BasicConfig from "../../../../utils/config";
import {
  hotelOrderAfterSaleStatus,
  orderActionEnum,
  orderRefundStatusConfig,
  orderSourceType,
  orderStatus,
  orderStatusConfig,
  searchOrderStatus,
} from "../../../../enums/order";
import { jumpPage } from "../../../../utils/route/route";
import { useImgSrc } from "../../../../hooks/useImg";
import { removeHtmlTags } from "../../../../utils/utils";
import { useUpdateRefund } from "../../../../hooks/useOrder";
import { useGetLocationStorage } from "../../../../hooks/useStorage";
import {
  useGetAuthLocation,
  useGetLocationAddress,
} from "../../../../hooks/useLocation";
dayjs.extend(duration);
const Instance = getCurrentInstance();
const $vm = Instance?.appContext.config.globalProperties;
const $data = reactive({
  localNo: "",
  orderServiceId: "",
  info: null,
  timer: null,
  remainingTime: 0,
  dayTime: "",
  douYinPayJson: null, // 抖音退款
  workSecondPrice: 0,
  goodsType: null, // 商品品类
  firstJoin: true, // 首次进入页面
});
const sdkData = reactive({
  mode: 1, // 组件使用模式 1.已下单 2.未下单
  orderStatus: 1, // mode为1时, 0：继续支付 ,1：申请退款,2：退款中,3：退款成功 ,4：退款失败
  orderId: "", // 开发者订单系统的交易订单号
  refundId: "", // 开发者订单系统的退款单号，用于查看退款详情； orderStatus为2,3,4时必传
  refundTotalAmount: 0, // 针对交易系统之前的老订单申请退款
  applyRefundParams: null, // 退款参数（仅uniapp或taro开发需要，原生抖音小程序不需要）
});
const onJump = (type) => {
  switch (type) {
    case orderActionEnum.reservation:
      jumpPage({
        to: "/package-service/pages/order/confirm",
        query: {
          localNo: $data.localNo,
          orderServiceId: $data.orderServiceId,
        },
      });
      break;
    case orderActionEnum.refund:
      jumpPage({
        to: "/package-service/pages/order/afterSales/apply",
        query: {
          localNo: $data.localNo,
          orderServiceId: $data.orderServiceId,
        },
      });
      break;
    default:
      break;
  }
};
const onReset = () => {
  if (isDown.value) {
    BasicConfig.toast("服务已下架");
    return;
  }
  jumpPage({
    to: "/package-service/pages/index",
    mode: "reLaunch",
    query: {
      id: $data.info.serviceSnapshot.domesticServiceId,
    },
  });
};
const onCopy = (text) => {
  uni.setClipboardData({
    data: text.toString(),
    success: (result) => {
      BasicConfig.toast("复制成功");
    },
    fail: (error) => {
      console.log("复制失败", error);
      BasicConfig.toast("复制失败!");
    },
  });
};
const init = () => {
  useUpdateRefund({
    localNo: $data.localNo,
    orderServiceId: $data.orderServiceId,
  }).then((res) => {
    console.log("useUpdateRefund", res);
    if (res.code === errorCode.success) {
      $data.douYinPayJson = res.data.douYinPayJson;
      $data.workSecondPrice = res.data.workSecondPrice;
      sdkData.orderStatus = res.data._orderStatus;
      sdkData.refundId = res.data.localNo;
      if ($data.douYinPayJson) {
        sdkData.refundTotalAmount = $data.douYinPayJson.total_amount;
      }
    }
  });
  getOrderDetail({
    localNo: $data.localNo,
    orderServiceId: $data.orderServiceId,
  }).then((res) => {
    if (res.code === errorCode.success) {
      $data.info = res.data;
      if ($data.info) {
        sdkData.orderId = $data.info.localNo;
        $data.goodsType = $data.info.dyGoodsType;
        setTitle();
        $data.info._picurl = useImgSrc($data.info.picurl);
        $data.info.addressSnapshot = $data.info.addressSnapshot ?? {};
        const { firstStartServicedAt, createdAt } = res.data;
        $data.info._firstStartServicedAt = firstStartServicedAt
          ? dayjs(firstStartServicedAt)
              .locale("zh-cn")
              .format("YYYY-MM-DD dddd HH:mm")
          : "";
        $data.info._createdAt = createdAt
          ? dayjs(createdAt).locale("zh-cn").format("YYYY-MM-DD dddd HH:mm")
          : "";
      }
    }
  });
};

const setTitle = () => {
  uni.setNavigationBarTitle({
    title: "待预约", // orderStatusConfig[$data.info.firstStatus]?.label ?? "",
  });
};
/** 是否下架 domesticServiceStatus 0.已下架 1.已上架 */
const isDown = computed(() => {
  const { domesticServiceStatus } = $data.info;
  return domesticServiceStatus == 0;
});
onLoad(async (options) => {
  $data.firstJoin = true;
  $data.localNo = options.localNo;
  $data.orderServiceId = options.orderServiceId;
  const LocationStorage = useGetLocationStorage() || {
    name: "未获取定位",
    code: null,
  };
  const auth = await useGetAuthLocation();
  if (!LocationStorage?.code || !auth) {
    try {
      await useGetLocationAddress().then((res) => {
        loadData();
      });
    } catch (error) {
      loadData();
    }
  } else {
    loadData();
  }
});
const loadData = async () => {
  setTimeout(async () => {
    $data.firstJoin = false;
    init();
  }, 100);
};
onShow(() => {
  if (!$data.firstJoin) {
    nextTick(() => {
      init();
    });
  }
});
onUnload(() => {});
onReady(() => {});
</script>
<style lang="scss" scoped>
@import "../../../static/style/order/detail/common.scss";
</style>
